package com.xbts.web.controller.huawei;

import com.xbts.common.config.XbtsConfig;
import com.xbts.common.core.controller.BaseController;
import com.xbts.common.core.redis.RedisCache;
import com.xbts.common.exception.ServiceException;
import com.xbts.common.utils.StringUtils;
import com.xbts.system.domain.metadata.MetadataBean;
import com.xbts.system.domain.saml.AuthnRequestResolution;
import com.xbts.system.domain.saml.SAMLResponseResolution;
import com.xbts.system.service.IHuaweiAccountService;
import lombok.extern.slf4j.Slf4j;
import org.opensaml.saml2.core.AuthnRequest;
import org.opensaml.saml2.core.Response;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Map;

@Slf4j
@RestController
@RequestMapping("/saml")
public class HuaweiSamlController extends BaseController{

    private final String USER_TO_HUAWEI = "USER_TO_HUAWEI";


    @Autowired
    private RedisCache redisCache;


    /**
     * https://support.huaweicloud.com/api-bpconsole/mc_00021.html
     * 查询客户列表
     * @return
     */
    @PostMapping(value = "/logout")
    public void samlLogout() {
        log.info("saml/logout-----------!");
    }

    /**
     * saml登录
     * @return
     */
    @GetMapping(value = "/login")
    public synchronized void samlLogin(HttpServletRequest request, HttpServletResponse response) throws Exception {
            // 获取请求地址
        log.info("华为云SAML登录····················！requestURL: {}", request.getRequestURL());
        String scheme = request.getScheme();
        log.info("协议scheme: {}", scheme);
        // 获取点击跳转的用户信息
        Map<String, Object> cacheMap = (Map<String, Object>) redisCache.getCacheObject(USER_TO_HUAWEI);
        log.info("用户信息-----------{}", cacheMap);
        if(StringUtils.isNull(cacheMap)){
            log.error("未查询到用信息！");
        }

        AuthnRequestResolution authnRequestResolution = new AuthnRequestResolution(request);
        try {
            // 解析SAMLRequest
            AuthnRequest authnRequest = authnRequestResolution.resolve(request);
            log.debug("resolve authnrequest successfully!  " + authnRequest.toString() );
            // SAMLRequest验签
            String spMetadataPath = XbtsConfig.getSpMetadataPath();
            MetadataBean spMetadata = new MetadataBean(spMetadataPath);
            log.debug("get SP metadata successfully!");
            if (!authnRequestResolution.verifySignature(spMetadata)) {
                throw new Exception("verifySignature error!");
            }
            log.debug("verify authnrequest signature successfully!");
            log.debug("验签通过!");
            // 生成SAMLResponse
            SAMLResponseResolution samlResponseResolution = new SAMLResponseResolution();
            Response samlResponse = samlResponseResolution.createSamlResponse(authnRequest, spMetadata, cacheMap);
            log.debug("resolve saml response successfully!");
            log.debug("创建 saml response 成功!");

            // 签名
            samlResponseResolution.signAssertion(samlResponse);
            log.debug("sign saml response successfully!");

            // 发送SAMLResponse
            samlResponseResolution.send(authnRequest.getAssertionConsumerServiceURL(), response, request, samlResponse);
            log.debug("send saml response successfully!");
        } catch (Exception e) {
            log.error("[error Message] decode SAMLRequest error !" + e.getMessage());
            response.setStatus(500);
            response.getWriter().println(e.getMessage());
        }
    }

}
